/*

Copyright 2009 Nicola Dal Pont

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

package com.astoolkit.workflow
{
	import com.astoolkit.workflow.constant.EMPTY_PIPELINE;
	import com.astoolkit.workflow.constant.EmptyPipelinePolicy;
	import com.astoolkit.workflow.constant.FailurePolicy;
	import com.astoolkit.workflow.constant.Feed;
	import com.astoolkit.workflow.constant.Flow;
	import com.astoolkit.workflow.constant.TaskStatus;
	import com.astoolkit.workflow.constant.UNDEFINED;
	
	import mx.collections.IList;
	import mx.events.PropertyChangeEvent;
	import mx.events.PropertyChangeEventKind;
	import mx.rpc.Fault;
	import mx.states.OverrideBase;

	public class SyncRepeaterWorkflow extends RepeaterWorkflow
	{
		private var _wasAborted : Boolean = false;

		override public function begin(inRetain:Boolean=false):void
		{
			_subPipelineData = UNDEFINED;
			_wasAborted = false;
			_currentDataIndex = -1;
			if( !dataProvider )
			{
				if(_pipelineData is IList )
					dataProvider = _pipelineData;
				else
					trace();
			}

			if(!_delegate)
				_delegate = createDelegate();
			if( !_parent )
				initialize();
			if( !_parent )
				prepare();
			_status = TaskStatus.RUNNING;
			_delegate.onBegin( this );
			if( !declaredTasks || declaredTasks.length == 0 || !dataProvider || dataProvider.length == 0 )
			{
				complete();
				return;
			}
			
			for each( var item : Object in dataProvider )
			{
				_subPipelineData = UNDEFINED;
				_nextTaskIndex = 0;
				try
				{
					produceTasks();
				}
				catch( e : Error )
				{
					fail( e.getStackTrace() );
					return;
				}

				var task : IWorkflowTask;
				for each( task in declaredTasks )
					task.prepare();
				dispatchEvent( 
					new PropertyChangeEvent( 
						PropertyChangeEvent.PROPERTY_CHANGE,
						false,
						false,
						PropertyChangeEventKind.UPDATE,
						"currentDataIndex",
						_currentDataIndex - 1,
						_currentDataIndex,
						this ) );
				dispatchEvent( 
					new PropertyChangeEvent( 
						PropertyChangeEvent.PROPERTY_CHANGE,
						false,
						false,
						PropertyChangeEventKind.UPDATE,
						"currentData",
						null,
						item,
						this ) );
				for each( task in declaredTasks )
				{
					if( _wasAborted )
					{
						complete();
						return;
					}
					
					if( task.enabled && ( !(task is IPipelineTask) || ( IPipelineTask( task ).emptyPipelinePolicy != EmptyPipelinePolicy.SKIP || _subPipelineData != EMPTY_PIPELINE ) ) )
					{
						setSubtaskPipelineData( task );
						try
						{
							task.begin( false );
							if( task is IPipelineTask )
								_subPipelineData = IPipelineTask( task ).taskOutput;
						}
						catch( e : Error )
						{
							if( task.failurePolicy == FailurePolicy.ABORT )
							{
								fail( e.getStackTrace() );
								complete();
								return;
							}
						}
					}
					_nextTaskIndex++;
				}
				
			}
			complete();
		}

		[Inspectable(defaultValue="serial", enumeration="serial,none")]
		override public function set flow(inFlow:String):void
		{
			if( inFlow != Flow.SERIAL && inFlow != Flow.NONE )
			{
				throw new Error(
					"SyncRepeaterWorkflow 'flow' property can only be either 'serial' or 'none': " +
					"found '" + inFlow + "'" );
			}
			_flow = inFlow;
		}
		
		override protected function onSubtaskBegin(inTask:IWorkflowTask):void
		{
			dispatchTaskEvent( WorkflowEvent.STARTED, inTask );
		}
		
		override protected function onSubtaskProgress(inTask:IWorkflowTask):void
		{
			dispatchTaskEvent( WorkflowEvent.STARTED, inTask );
		}
		
		override protected function onSubtaskFault(inTask:IWorkflowTask, inMessage:String, inFault:Fault):void
		{
			dispatchTaskEvent( WorkflowEvent.FAULT, inTask );

		}
		
		override protected function onSubtaskAbort(inTask:IWorkflowTask, inMessage:String):void
		{
			dispatchTaskEvent( WorkflowEvent.ABORTED, inTask );

		}
		
		override protected function onSubtaskWarning(inTask:IWorkflowTask, inMessage:String, inError:Fault):void
		{
			dispatchTaskEvent( WorkflowEvent.WARNING, inTask );

		}
		override protected function onSubtaskCompleted( inTask : IWorkflowTask ) : void
		{
			dispatchTaskEvent( WorkflowEvent.COMPLETED, inTask );

		}
		
		override protected function complete() : void
		{
			if( _feed == Feed.PIPELINE || _feed == Feed.CURRENT_DATA )
				_pipelineData = _subPipelineData;
			_delegate.onComplete( this );
			if( !parent )
				cleanUp();
		}
		
		override public function abort():void
		{
			_wasAborted = true;
		}
		
		

	}
}